#ifndef NETWORKCLIENT_H
#define NETWORKCLIENT_H

#include <QThread>
#include <QtNetwork/QHostAddress>
#include <QtNetwork/QSslSocket>

#include "userdata.h"
#include "logentry.h"

class NetworkClient : public QThread
{
    Q_OBJECT
public:
     NetworkClient(QObject *parent = 0);

signals:
    /* User session signals */
    void logInFailed(const QString &);
    void logInSuccessful(UserData *);
    void alreadyAttemptingConnection();
    void badReplyReceived(const QString &);
    void logOutSuccess();
    void sslError(const QString &);

    /* Log retrieval signals */
    //For User Window: writing new entry
    void newLogEntrySuccessful(const QString &);
    void newLogEntryError(const QString &);

    //For User Window: Loading owner's logs from DB
    void logReadyToRead(LogEntry *);
    void logReadError(const QString &);

    //For Management Window & username QDialog: listing all usernames
    void userListReady(QStringList *);
    void userListError(const QString &);
    void newUserAdded(const QString &);//* addNewUserSuccess();
    void newUserNotAdded(const QString &);//* addNewUserFailed();
    void userRemoved();//* removeUserSuccess();
    void userRemoveFailed(const QString &);//* removeUserFailed();
    void accessAddSuccess();
    void accessAddFailed(const QString &);
    void accessRemoveSuccess();
    void accessRemoveFailed(const QString &);

public slots:
    /* Log-in slots */
    void attemptLogIn(UserData *);
    void attemptLogOut();
    void changeServerAddress(const QString &, int);

    /* Logging/log retrieval signals */
    void sendNewLog(LogEntry *);
    //For ViewOtherLog when chosen specific username from comboBox
    void requestLogs(QStringList *);

    /* Management */
    void requestAllUsers(UserData *);
    void newUserRequest(UserData *); //* addNewUser()
    void removeUserRequest(UserData *); //* removeUser()
    void addAccessRequest(const QString &, const QString &);
    void removeAccessRequest(const QString &, const QString &);

private slots:
    /* Connection slots */
    void socketStateChanged(QAbstractSocket::SocketState);
    void sslErrors(QList<QSslError>);
    void socketConnected();
    void socketEncrypted();
    void socketReadyRead();

private:
    /* connection members */
    QSslSocket *socket;
    QHostAddress *serverAddress;
    int serverPort;

    QString userName;
    UserData *user;
    /* status members */
    bool unconnected, connected;
    bool loggedIn, waitingForLogs, waitingForUserList, waitingForMgmntFunction;

    void badReply(const QString &, const QString &);
    void checkLoginReply();
    void readLogReply();
    void readUserList();
    void checkMgmntReply();
    void checkReply();
};

#endif // NETWORKCLIENT_H
